package battleship;

import org.apache.catalina.Session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

public class GameOverServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("GameOverServlet: starting");
    	String userToken= request.getParameter("token");
    	int id= (Integer) UserIdTokenHashMap.idTokenMap.get(userToken);
        //int id = Integer.parseInt(request.getParameter("id"));

        User user = Context.users[id];
        
        User winner = new User();
        try {
            winner = user.gameOver.take();
            System.out.println("got the winner from the gameoverqueue");
        } catch (InterruptedException e) {
            System.out.println("GameOverServlet exception: " + e.getMessage());
        }

        Game game = user.game;
        Context.currentGames.remove(game);
        user.playing = false;
        user.inLobby = true;
        user.donePlacingShips = false;
        user.opponentID = -1;
        user.ships = new ArrayList<ArrayList<int[]>>();
        user.startingPlayer = false;
        user.hit = new ArrayList<int[]>();
        user.sunk = new ArrayList<int[]>();


        PrintWriter out = response.getWriter();
        response.setContentType("text/plain");
        
        if (user.equals(winner)) {
            out.print("you");
            Databasetest.addScores(user.username, 1);
        } else {
            out.print("opponent");
            Databasetest.addScores(user.username, 0);
        }

        // kui game over, siis kirjutada andmebaasi võitja.

        
        System.out.println("GameOverServlet: finished");
    }
}
